package com.thinkit.cms.strategy.actuator;

import com.thinkit.cms.strategy.checker.ActuatorCheck;
import com.thinkit.cms.strategy.checker.PublishChecker;
import com.thinkit.cms.strategy.convers.CategoryConvert;
import com.thinkit.cms.strategy.convers.ContentConvert;
import com.thinkit.cms.strategy.filter.FilterChain;
import com.thinkit.cms.strategy.filter.TmpActuator;
import com.thinkit.core.annotation.Actuator;
import com.thinkit.core.constant.Channel;
import com.thinkit.utils.enums.ActionEnum;
import com.thinkit.utils.enums.ChannelEnum;
import com.thinkit.utils.utils.Checker;
import com.thinkit.utils.utils.SpringContextHolder;
import lombok.Getter;
import lombok.Setter;
import org.quartz.JobExecutionContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页模板生成执行器
 */
@Actuator(code ="CONTENT_DETAIL_ACTUATOR",name = "内容详情模板生成执行器")
public class ContentActuator extends TmpActuator  {

    @Getter @Setter
    private Object params;

    @Getter @Setter
    private ActionEnum actionEnum;

    private ContentConvert contentConvert;

    public ContentActuator(){
        super();
    }

    public ContentActuator(Object params,ActionEnum actionEnum){
       super();
       this.params = params;
       this.actionEnum = actionEnum;
       this.contentConvert = SpringContextHolder.getBean(ContentConvert.class);
    }


    @Override
    public void doFilter(Object params, FilterChain chain) {
        if(Checker.BeNull(params)){
            params = this.params;
        }
        if(isNotJob()) {
            ActuatorCheck actuatorCheck = super.actuatorCheck;
            if(actuatorCheck instanceof PublishChecker && Checker.BeNotNull(params)){
                PublishChecker publishChecker = (PublishChecker) actuatorCheck;
                List<Map<String,Object>> contents =contentConvert.convertParam(publishChecker.getContents());
                for( Map<String,Object> content :contents){
                    sendMag(content);
                }
            }else{
                Map<String,Object> content =contentConvert.convertParam(params,actionEnum);
                sendMag(content);
            }
        }else{
            chain.addJobFilter(this);
        }
        chain.doFilter(params,chain);
    }

    private void sendMag(Map<String,Object> content){
        if(Checker.BeNotNull(content) && !content.isEmpty()){
            messageSend.sendMessage(ChannelEnum.CONTENT, Channel.NOTIFY_IT,content);
        }
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext)  {
        Map dateMap = jobExecutionContext.getJobDetail().getJobDataMap();
        Map<String,Object> content =contentConvert.convertParam(dateMap,actionEnum);
        messageSend.sendMessage(ChannelEnum.CONTENT, Channel.NOTIFY_IT,content);
    }


    public Object getParam(){
        return this.params;
    }

}
